package com.bishe.cyh.utils;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Enumeration;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;

/**
 * @Author: Poppin
 * @Date: 2022/1/11 21:59
 * @Version: 1.0
 */
public class ZipUtils {


    //解压
    public static void decompress(String srcPath,String dest) throws IOException {
        File file = new File(srcPath);

        if (!file.exists()){
            throw new RuntimeException(srcPath+"文件不存");
        }

        ZipFile zf = new ZipFile(file);
        Enumeration entries = zf.entries();

        ZipEntry entry = null;
        while (entries.hasMoreElements()){
            entry = (ZipEntry) entries.nextElement();

            if (entry.isDirectory()){
                String dirPath = dest + File.separator + entry.getName();
                File dir = new File(dirPath);
                dir.mkdir();
            }
            else {
                File f = new File(dest+File.separator+entry.getName());
                if (!f.exists()){
                    String dirs = f.getParent();
                    File parentDir = new File(dirs);
                    parentDir.mkdirs();
                }
                f.createNewFile();
                InputStream is = zf.getInputStream(entry);
                FileOutputStream fos = new FileOutputStream(f);
                int count;
                byte[] buf = new byte[8192];
                while ((count = is.read(buf)) != -1){
                    fos.write(buf,0,count);
                }
                is.close();
                fos.close();
            }
        }
    }

    //计算解压后的大小
    public static long getTotalSizeOfFilesInDir(File file){
        if (file.isFile())
            return file.length();
        File[] children = file.listFiles();
        long total = 0;
        if (children!=null){
            for (File child:children){
                total+= getTotalSizeOfFilesInDir(child);
            }
        }
        return total;
    }


}
